package com.huangliusong.order.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.huangliusong.order.dataobject.OrderDetail;
import com.huangliusong.order.dto.OrderDTO;
import com.huangliusong.order.enums.ResultEnum;
import com.huangliusong.order.exception.OrderException;
import com.huangliusong.order.form.OrderForm;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @author huangliusong
 * @since 2018/10/26
 * {@link }
 */
@Slf4j
public class OrderForm2OrderDto {
    public static OrderDTO convert(OrderForm orderForm){
        OrderDTO orderDTO=new OrderDTO();
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerAddress(orderForm.getAddress());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());

        List<OrderDetail> orderDetails=new ArrayList<>();

        Gson  gson=new Gson();
        try {
            orderDetails=gson.fromJson(orderForm.getItems(),
                    new TypeToken<List<OrderDetail>>(){}.getType());

        }catch (Exception e){
            log.error("json转换出错 str",orderForm.getItems());
            throw new OrderException(ResultEnum.PARAM_ERROR);
        }
        orderDTO.setOrderDetailsList(orderDetails);

        return orderDTO;
    }
}
